import 'package:flutter/material.dart';

import '../../config/Config.dart';

class TextOption extends StatefulWidget {

  final List<String> options;

  final int type;

  final String value;

  final ValueChanged<String> onChanged;

  const TextOption({super.key,required this.options,required this.type,required this.value,required this.onChanged});

  @override
  State<TextOption> createState() => _TextOptionState();
}

class _TextOptionState extends State<TextOption> {

  late String result = "";

  @override
  void initState() {
    super.initState();
    setState(() {
      result = widget.value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 4,
        mainAxisSpacing: 8,
        crossAxisSpacing: 8,
        childAspectRatio: 2 / 1,
      ),
      itemCount: widget.options.length,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemBuilder: (context, index) {
        var selected = result.split(",").contains(widget.options[index]);
        print("selected:$selected");
        return GestureDetector(
          onTap: () {
            String newResult = result;
            if(widget.type==0){
              newResult = widget.options[index];
              widget.onChanged(widget.options[index]);
            }else if(widget.type==1){
              var split = newResult.split(",");
              split.add(widget.options[index]);
              newResult = split.join(",");
              widget.onChanged(newResult);
            }
            setState(() {
              result = newResult;
            });
          },
          child: Container(
            decoration: BoxDecoration(
              border: Border.fromBorderSide(
                BorderSide(
                  color: selected ? Config.primaryColor : Config.colorA3b5e3,
                  width: 1.0,
                ),
              ),
              borderRadius: BorderRadius.circular(8.0),
              color: selected ? Config.primaryColor : Colors.white,
            ),
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8),
              child: Center(
                child: Text(
                  maxLines: 8,
                  widget.options[index],
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 12,
                      color: selected ? Colors.white : Colors.black),
                ),
              ),
            ),
          ),
        );
      },
    );;
  }
}
